// AlarmModule.java

package com.flife;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;

import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import com.flife.R; // 添加对应的 R 文件引用

public class AlarmModule extends ReactContextBaseJavaModule {
    private static final String TAG = "AlarmModule";

    private final ReactApplicationContext reactContext;
    private AlarmManager alarmManager;

    public AlarmModule(ReactApplicationContext context) {
        super(context);
        this.reactContext = context;
        this.alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    }

    @Override
    public String getName() {
        return "AlarmModule";
    }

    @ReactMethod
    public void setAlarm(int seconds) {
        

        try {
            Log.d("AlarmModule", "Setting alarm...");
            Intent intent = new Intent(reactContext, AlarmReceiver.class);
            PendingIntent pendingIntent = PendingIntent.getBroadcast(reactContext, 0, intent, PendingIntent.FLAG_IMMUTABLE);

            long triggerTime = System.currentTimeMillis() + (seconds * 1000);

            alarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, pendingIntent);

            // 创建通知
            NotificationCompat.Builder builder = new NotificationCompat.Builder(reactContext, "channel_id")
                .setSmallIcon(R.mipmap.ic_launcher) // 设置默认图标
                .setContentTitle("Alarm Set")
                .setContentText("Alarm will trigger in " + seconds + " seconds")
                .setPriority(NotificationCompat.PRIORITY_DEFAULT);

            NotificationManagerCompat notificationManager = NotificationManagerCompat.from(reactContext);

            // 发送通知
            notificationManager.notify(1, builder.build());
            
            Log.d("AlarmModule", "Alarm set successfully. " + triggerTime + "和" + pendingIntent);
        } catch (Exception e) {
            Log.e("AlarmModule", "Error setting alarm: " + e.getMessage());
        }
    }
}
